import os
from config import TEMPLATE_PATH


class FileSource:
    def __init__(self):
        self.path = ''

    def open(self, filename):
        self.path = os.path.join(TEMPLATE_PATH, filename)

    def __getitem__(self, item):
        fr = open(self.path, 'r')
        if isinstance(item, int):
            fr.seek(item, 0)
            return fr.read(1)
        elif isinstance(item, slice):
            # parse slice
            l = os.path.getsize(self.path)
            # start
            if item.start:
                if item.start >= 0:
                    start = item.start
                else:
                    start = l + item.start
            else:
                start = 0
            # step
            if item.step:
                step = item.step
            else:
                step = 1
            # stop
            if item.stop:
                if item.stop >= 0:
                    stop = item.stop
                else:
                    stop = l + item.stop
            else:
                stop = l
            # read
            text = ''
            i = start
            while i != stop:
                fr.seek(i, 0)
                text += fr.read(1)
                i += step
            return text

    def __len__(self):
        return os.path.getsize(self.path)

    def __iter__(self):
        fr = open(self.path, 'r')
        for line in fr:
            for char in line:
                yield char

    def __repr__(self):
        fr = open(self.path, 'r')
        return fr.read()

    def __str__(self):
        return self.__repr__()